//
//  EMLoginViewController.m
//  LoginAndReg
//
//  Created by fortsven on 14/12/23.
//  Copyright (c) 2014年 hoperun. All rights reserved.
//

#import "EMLoginViewController.h"
#import "EMInputTextField.h"
#import "UINavigationController+EMNavi.h"
#import "EMRegisterViewController.h"
#import "EMLoginReqBody.h"
#import "EMLoginRespBody.h"
#import "EMOtherLoginReqBody.h"
#import "EMOtherLoginRespBody.h"
#import "UserInfo.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "EMFetchPasswordViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "MyMD5.h"
@interface EMLoginViewController ()
{
    AppDelegate *app;
    EMInputTextField *userNameTF;
    EMInputTextField *userPassTF;
}

@end

@implementation EMLoginViewController
- (void)hideBottomBar
{
    for(UIView *view in self.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
            view.hidden = YES;
    }
}
- (void)viewWillAppear:(BOOL)animated
{    
    [super viewWillAppear:animated];
    [self hideBottomBar];
    self.view.backgroundColor = RGB(242, 242, 242);

    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.navigationItem.title = @"用户登录";
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 32);
    [button setImage:[UIImage imageNamed:@"button_导航_返回_白"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    
    UIButton *regButton =[UIButton buttonWithType:UIButtonTypeCustom];
    regButton.frame=CGRectMake(0, 0, 40, 32);
    regButton.titleLabel.font = [UIFont fontWithName:HEITILIGHT size:16];
    [regButton setTitle:@"注册" forState:UIControlStateNormal];
    [regButton addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:regButton];
    
}
- (void)backAction: (UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)registerAction:(UIButton *)sender
{
    EMRegisterViewController *controller = [[EMRegisterViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    scrollView.contentSize = CGSizeMake(W(320), H(800));
    
    int height = 25;
    userNameTF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(40))];
    userNameTF.placeholderText = @"请输入用户名";
    userNameTF.logoName = @"icon_输入框_用户";
    
    [userNameTF setTextFieldMode:EMInputTextFieldModeLogoAndText];
    userNameTF.inputTextField.delegate = self;
    [scrollView addSubview:userNameTF];
    
    height += 40 + 15;
    userPassTF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(40))];
    userPassTF.placeholderText = @"请输入密码";
    userPassTF.logoName = @"icon_输入框_密码";
    [userPassTF setTextFieldMode:EMInputTextFieldModeLogoAndText];
    userPassTF.inputTextField.delegate = self;
    [scrollView addSubview:userPassTF];

    UIButton *forgetPwd = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    forgetPwd.frame = CGRectMake(W(240), H(height + 45), W(70), H(16));
    [forgetPwd setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [forgetPwd setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    forgetPwd.titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [forgetPwd addTarget:self action:@selector(forgetAction:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:forgetPwd];
    
    height += 40 + 80;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(W(10), H(height), W(300), H(40));
    btn.backgroundColor = RGB(112, 179, 81);
    btn.layer.cornerRadius = 5;
    btn.titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:20];
    [btn setTitle:@"登陆" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(userLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:btn];
    
    UIImageView *leftSepLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line_快速登录分割线"]];
    leftSepLine.frame = CGRectMake(W(10), H(280), W(100), 2);
    [scrollView addSubview:leftSepLine];
    
    UILabel *sepLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(115), H(275), W(90), H(12))];
    sepLabel.text = @"快速登录";
    sepLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
    sepLabel.textAlignment = NSTextAlignmentCenter;
    [scrollView addSubview:sepLabel];
    
    UIImageView *rightSepLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line_快速登录分割线"]];
    rightSepLine.frame = CGRectMake(W(210), H(280), W(100), 2);
    [scrollView addSubview:rightSepLine];
    
    UIButton *qqLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    qqLogin.frame = CGRectMake(W(10), H(300), W(145), H(80));
    [qqLogin setImage:[UIImage imageNamed:@"button_QQ登陆"] forState:UIControlStateNormal];
    [qqLogin addTarget:self action:@selector(qqLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:qqLogin];
    
    UIButton *wcLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    wcLogin.frame = CGRectMake(W(165), H(300), W(145), H(80));
    [wcLogin setImage:[UIImage imageNamed:@"button_微信登录"] forState:UIControlStateNormal];
    [wcLogin addTarget:self action:@selector(wcLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:wcLogin];
    
    [self.view addSubview:scrollView];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackground:)];
    [self.view addGestureRecognizer:tapGR];
}


#pragma mark - 关闭键盘
- (void)tapBackground:(UIGestureRecognizer *)recog
{
    [self closeKeyboard];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self closeKeyboard];
    return NO;
}

- (void)closeKeyboard
{
    [userNameTF.inputTextField resignFirstResponder];
    [userPassTF.inputTextField resignFirstResponder];
}


#pragma mark - 点击事件
- (void)forgetAction:(UIButton *)sender
{
    EMFetchPasswordViewController *controller = [[EMFetchPasswordViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)userLoginAction:(UIButton *)sender
{
    if ([userNameTF.inputTextField.text isEqualToString:@""] || userNameTF.inputTextField.text == nil) {
        [app showTip:@"请输入用户名"];
        return;
    }
    if ([userPassTF.inputTextField.text isEqualToString:@""] || userPassTF.inputTextField.text == nil) {
        [app showTip:@"请输入密码"];
        return;
    }
    
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    NSLog(@"%@: %@", userNameTF.inputTextField.text, userPassTF.inputTextField.text);
    EMLoginReqBody *reqBody = [[EMLoginReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"USER-LOGIN";
    reqBody.USERID = userNameTF.inputTextField.text;
    reqBody.PASSWORD = userPassTF.inputTextField.text;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMLoginRespBody *respBody = [EMLoginRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            [UserInfo sharedUserInfo].m_isLogin = YES;
            [UserInfo sharedUserInfo].m_session = respBody.SESSION;
            [UserInfo sharedUserInfo].m_userName = respBody.USERNAME;
            [UserInfo sharedUserInfo].m_nickName = respBody.USERNAME;
            [self.navigationController popViewControllerAnimated:YES];
            [app showTip:@"登录成功"];
            
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    
}

- (void)otherLoginRequestWithSign:(NSString *)sign andUserId:(NSString *)userId
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMOtherLoginReqBody *reqBody = [[EMOtherLoginReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"UserReg_qq_weixin";
    reqBody.USERID = userId;
    reqBody.SIGN = sign;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMOtherLoginRespBody *respBody = [EMOtherLoginRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            [UserInfo sharedUserInfo].m_isLogin = YES;
            [UserInfo sharedUserInfo].m_session = respBody.SESSION;
            [UserInfo sharedUserInfo].m_userName = respBody.USERNAME;
            [self.navigationController popViewControllerAnimated:YES];
            [app showTip:@"登录成功"];
            
        } else {
            
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];

}

- (void)qqLoginAction:(UIButton *)sender
{
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                      allowCallback:YES
                                                      authViewStyle:SSAuthViewStyleFullScreenPopup
                                                       viewDelegate:nil
                                            authManagerViewDelegate:nil];
    
    [ShareSDK getUserInfoWithType:ShareTypeQQSpace authOptions:authOptions result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
        
        NSLog(@"tecentqq-%d－－－\n%@", result, userInfo);
        if (result) {
            [UserInfo sharedUserInfo].m_nickName = [NSString stringWithFormat:@"%@(qq用户)", [userInfo nickname]];
            [self otherLoginRequestWithSign:@"1" andUserId:[NSString stringWithFormat:@"%@",[userInfo uid]]];
        }
    }];
}
- (void)wcLoginAction:(UIButton *)sender
{
    [ShareSDK getUserInfoWithType:ShareTypeWeixiSession authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
        NSLog(@"weixin-%d－－－\n%@", result, userInfo);
        if (result) {
            [UserInfo sharedUserInfo].m_nickName = [NSString stringWithFormat:@"%@(微信用户)", [userInfo nickname]];
            [self otherLoginRequestWithSign:@"2" andUserId:[NSString stringWithFormat:@"%@@weixin",[userInfo uid]]];
        }
    }];
}


@end
